package cn.flant.report;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import jxl.Sheet;
import jxl.Workbook;

public class ExcelUtil {

	public static String[][] getExcelData(String fileName, int sheetIdx) {
		return getExcelData(new File(fileName), sheetIdx);
	}

	public static String[][] getExcelData(File file, int sheetIdx) {
		Workbook book = null;
		try {
			book = Workbook.getWorkbook(file);
			Sheet sheet = book.getSheet(sheetIdx);
			return sheetToData(sheet);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (book != null) {
				book.close();
			}
		}
		return null;
	}

	public static Map<String, String[][]> getExcelDatas(String fileName) {
		return getExcelDatas(new File(fileName));
	}

	public static Map<String, String[][]> getExcelDatas(File file) {
		Workbook book = null;
		try {
			book = Workbook.getWorkbook(file);
			Map<String, String[][]> datas = new HashMap<String, String[][]>();
			String[] sheetNames = book.getSheetNames();
			for (String sheetName : sheetNames) {
				Sheet sheet = book.getSheet(sheetName);
				String[][] data = sheetToData(sheet);
				datas.put(sheetName, data);
			}
			return datas;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (book != null) {
				book.close();
			}
		}
		return null;
	}

	private static String[][] sheetToData(Sheet sheet) {
		int row = sheet.getRows();
		int col = sheet.getColumns();
		String[][] data = new String[row][col];
		for (int j = 0; j < row; j++) {
			for (int k = 0; k < col; k++) {
				data[j][k] = sheet.getCell(k, j).getContents().trim();
			}
		}
		return data;
	}

	public static void main(String[] args) {
	}
}
